package com.zztl.infiniteBand.presenter

import android.util.Log
import com.zztl.infiniteBand.base.BasePresenter
import com.zztl.infiniteBand.net.FilterSubscriber2
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.imp.DownLoadListener
import com.zztl.infiniteBand.ui.view.mvpview.MvpView
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

/**
 * @desc
 * @auth ${user}
 * @time 2018/11/14  18:41
 */
open class DownLoadFilePresenter : BasePresenter<MvpView>() {
    fun downLoad(url: String, filePath: String, loadListener: DownLoadListener) {
        RetorfitServiceManger.reSetRetroServiceManager()
        RetorfitServiceManger.setLoadListener(loadListener)
        addSubscribe(RetorfitServiceManger.instance!!.apiService.loadFile(url).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io()).map({ responseBody -> responseBody.byteStream() })
                .observeOn(Schedulers.io())
                .doOnNext({ inputStream -> writeFile(inputStream, filePath) })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : FilterSubscriber2<InputStream>(null) {
                    override fun success(inputStream: InputStream) {

                    }

                     override fun fail(message: String?) {
                        loadListener.loadError(message!!)
                    }

                    override fun onCompleted() {
                        loadListener.loadFinish()
                    }


                    override fun onStart() {
                        loadListener.startLoad()
                    }
                }))

    }


    private fun writeFile(inputStream: InputStream, filePath: String) {
        val fileDir = File("sdcard/IFRSport/")
        if (!fileDir.exists()) {
            fileDir.mkdir()
        }
        //        File file=new File()
        val file = File(fileDir.absolutePath, filePath)
        if (file.exists()) {
            file.delete()
        }
        var ous: FileOutputStream? = null
        try {
            file.createNewFile()

            ous = FileOutputStream(file)
            val b = ByteArray(1024)
            var len: Int = -1
            while (inputStream.read(b).also { len = it } != -1) {
                ous.write(b, 0, len)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("swl", e.message)
        } finally {
            try {
                inputStream?.close()
                if (null != ous) {
                    ous.close()
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }


}
